package com.iyao_app.im.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.iyao_app.Friends.ChatActivity;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.IMUser;
import com.iyao_app.im.adapter.IMMessageListAdapter;
import com.iyao_app.im.nimsdk.NimRecentContactSDK;
import com.iyao_app.im.nimsdk.utils.NimMessageSDK;
import com.iyao_app.mvp.home.MainActivity;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.util.UserUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class IMMessageListActivity extends BaseActivityWithHead {

    @BindView(R.id.attention)
    ImageView mAttention;
    @BindView(R.id.attention_message)
    TextView mAttentionMessage;
    @BindView(R.id.rl_attention_message)
    RelativeLayout mRlAttentionMessage;
    @BindView(R.id.system)
    ImageView mSystem;
    @BindView(R.id.system_message)
    TextView mSystemMessage;
    @BindView(R.id.rl_system_message)
    RelativeLayout mRlSystemMessage;
    @BindView(R.id.cvMessage)
    RecyclerView mCvMessage;
    @BindView(R.id.friend_hint)
    TextView mFriendHint;

    private IMMessageListAdapter imMessageListAdapter;
    private static List<IMMessage> emMessageList = new ArrayList<IMMessage>();
    private static Observer<List<IMMessage>> mIncomingMessageObserver;
    private static Observer<IMMessage> mMsgStatusObserver;
    private String toNickName;
    Context context;
    MainActivity mainActivity = (MainActivity) context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_immessage_list);
        ButterKnife.bind(this);

        init();
    }

    public void init() {
        setTitleTV(ResourcesUtils.getString(R.string.message));

        //最近会话列表
        observeHuiHua();

        observeReceiveMessage();

    }

    /**
     * 监听最近联系人
     */
    private void observeHuiHua() {
        NIMClient.getService(MsgService.class).queryRecentContacts()
                .setCallback(new RequestCallbackWrapper<List<RecentContact>>() {
                    @Override
                    public void onResult(int code, final List<RecentContact> recents, Throwable e) {

                        if (recents.size() == 0) {
                            mFriendHint.setVisibility(View.VISIBLE);
                        }else {
                            // recents参数即为最近联系人列表（最近会话列表）
                            mCvMessage.setLayoutManager(new StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL));
                            imMessageListAdapter = new IMMessageListAdapter(recents);
                            mCvMessage.setAdapter(imMessageListAdapter);

                            imMessageListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    RecentContact item = (RecentContact) adapter.getItem(position);
                                    Intent intent = new Intent(IMMessageListActivity.this, ChatActivity.class);
                                    intent.putExtra("username", item.getContactId());
                                    intent.putExtra("nickname", toNickName);
                                    startActivity(intent);
                                    //清空当前联系人的未读数
                                    NimRecentContactSDK.clearUnreadCount(item.getContactId(), item.getSessionType());
                                }
                            });
                        }
                    }
                });

    }

    private void observeReceiveMessage() {
        mIncomingMessageObserver = new Observer<List<IMMessage>>() {

            @Override
            public void onEvent(List<IMMessage> imMessages) {
                if (imMessages == null || imMessages.isEmpty()) {
                    return;
                } else {
                    emMessageList = imMessages;
                    for (IMMessage imMessage : imMessages) {
                        Map<String, Object> remoteExtension = imMessage.getRemoteExtension();
                        LogUtil.e("==imMessage===>" + imMessage.toString() + "===" + imMessage.getSessionId() + "===" + imMessage.getUuid());
                        LogUtil.e("==remoteExtension===>" + remoteExtension);
                        if (remoteExtension != null) {
                            String fromNickName = (String) remoteExtension.get("fromNickName");
                            String toAvatar = (String) remoteExtension.get("toAvatar");
                            toNickName = (String) remoteExtension.get("toNickName");
                            String fromAvatar = (String) remoteExtension.get("fromAvatar");

                            String sessionId = imMessage.getSessionId();
                            IMUser imUser = new IMUser();
                            imUser.userId = sessionId;
                            imUser.head = fromAvatar;
                            imUser.nickName = fromNickName;
                            UserUtils.addUser(imUser);
                        }
                    }

                    observeHuiHua();
//                    Map<String, Object> remoteExtension = imMessages.get(position).getRemoteExtension();
//                    if (remoteExtension != null) {
//                        fromNickName = (String) remoteExtension.get("fromNickName");
//                        String toAvatar = (String) remoteExtension.get("toAvatar");
//                        toNickName = (String) remoteExtension.get("toNickName");
//                        String fromAvatar = (String) remoteExtension.get("fromAvatar");
//                    }else {
//
//                    }
                }
            }
        };
        //观察消息
        NimMessageSDK.observeReceiveMessage(mIncomingMessageObserver, true);
    }

    @OnClick({R.id.rl_attention_message, R.id.rl_system_message})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_attention_message:
                break;
            case R.id.rl_system_message:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        observeHuiHua();
    }
}
